package com.jeanbart.util;

import com.jeanbart.bean.Player;
import com.jeanbart.factory.wowsUrlFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import static java.lang.Thread.sleep;


public class WowsFutureTask {
    private List<Player> playerList;
    FutureTask<Object> task[] = new FutureTask[24];
    private int size=1;
    //n==1代表获取UID，2代表获取玩家胜率，3代表获取船的胜率
    public WowsFutureTask(List<Player> playerList, String service , int n) {
        this.playerList = playerList;
        this.size = playerList.size();
        switch (n) {
            case 1: //1的时候执行2
            case 2:
                if (!service.equals("CN")) {
                    this.size =-1;
                    this.task[0] = new FutureTask<Object>((Callable<Object>) new wowsUrlFactory().getWowsIns(service,null, playerList));
                    new Thread(this.task[0]).start();
                } else {
                    for (int i = 0; i < size; i++) {
                        this.task[i] = new FutureTask<Object>((Callable<Object>) new wowsUrlFactory().getWowsIns(service,playerList.get(i), null));
                        new Thread(this.task[i]).start();
                    }
                }
                break;
            case 3:
                    for (int i = 0; i < size; i++) {
                        this.task[i] = new FutureTask<Object>((Callable<Object>) new wowsUrlFactory().getWowsIns(service,playerList.get(i), null));
                        new Thread(this.task[i]).start();
                        try {
                            sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                break;
        }
    }
    public ArrayList<Player> getResult(){
        ArrayList<Player> List=new ArrayList<>();
        if(this.size==-1){
            try {
                this.task[0].get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }else {
            for (int i = 0; i < this.size; i++) {
                try {
                    this.task[i].get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
        return List;
    }
}
